<template>
  <view class="publish-page">
    <!-- 使用uView的表单组件 -->
    <up-form
        :model="formData"
        ref="formRef"
        labelPosition="top"
    >
      <!-- 顶部话题区域 -->
      <view class="topic-container">
        <view class="topic-tag-but" @click="showPopup = true">
          <up-icon type="hash" size="16" color="#39b54a"></up-icon>
          <text>加话题</text>
        </view>

        <view class="selected-topics">
          <view
              class="topic-tag"
              v-for="(tag, index) in selectedTags"
              :key="index"
          >
            {{ tag }}
            <view class="delete-tag" @click="removeTag(index)">×</view>
          </view>
        </view>
      </view>

      <!-- 内容输入 -->
      <up-form-item
          label="内容"
          prop="content"
          :borderBottom="false"
      >
        <textarea
            v-model="formData.content"
            placeholder="分享你的内容..."
            class="content-input"
            auto-height
        ></textarea>
      </up-form-item>

      <!-- 图片上传区域 -->
      <up-form-item
          label="图片"
          prop="files"
          :borderBottom="false"
      >
        <!-- 使用封装的上传组件 -->
        <my-upload
            v-model:files="formData.files"
            :max-count="9"
            upload-url="http://localhost:10000/oss/upload"
            file-type="article-file"
            user-id="123"
            @on-upload-error="handleUploadError"
            ref="uploadComponent"
        ></my-upload>
      </up-form-item>

      <!-- 发布按钮 -->
      <view class="form-button-container">
        <u-button
            class="publish-btn"
            @click="submitForm"
            :disabled="!canPublish || loading"
            type="primary"
            shape="circle"
        >
          <!-- 加载状态显示loading图标，否则显示文字 -->
          <template v-if="loading">
            <u-loading-icon size="24" color="#fff"></u-loading-icon>
          </template>
          <template v-else>
            发布
          </template>
        </u-button>
      </view>
    </up-form>

    <!-- 话题选择弹出层（底部弹出） -->
    <u-popup
        ref="popup"
        :show="showPopup"
        mode="bottom"
        @close="showPopup = false"
    >
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">选择话题</text>
          <u-icon name="close" size="24" @click="showPopup = false"></u-icon>
        </view>
        <view class="search-box">
          <u-search
              placeholder="搜索话题"
              v-model="searchKeyword"
              @input="onSearchInput"
          ></u-search>
        </view>
        <view class="topic-list">
          <view
              class="topic-item"
              v-for="(topic, index) in filteredTopics"
              :key="index"
              @click="selectTopic(topic)"
          >
            <text>{{ topic }}</text>
            <u-icon
                size="18"
                color="#007AFF"
                v-if="selectedTags.includes(topic)"
            ></u-icon>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script setup>
import {ref, computed} from 'vue';
import MyUpload from "@/components/upload/my-upload.vue";
import {publishArticle} from "@/apis/publish";

// 表单数据
const formData = ref({
  content: '',
  files: [],
  tags: []
});

// 表单引用
const formRef = ref(null);
// 上传组件引用
const uploadComponent = ref(null);

// 状态管理
const showPopup = ref(false);
const searchKeyword = ref('');
const allTopics = ref([
  '求助', '拼车', '找搭子', '捞人', '寻物启事',
  '失物招领', '活动', '交友', '校园生活', '兴趣爱好'
]);
const selectedTags = ref([]);
// 新增：加载状态，防止重复提交
const loading = ref(false);

// 发布按钮状态：内容或图片至少有一个，且不在加载中
const canPublish = computed(() => {
  return (formData.value.content.trim() || formData.value.files.length > 0) && !loading.value;
});

// 过滤后的话题列表
const filteredTopics = computed(() => {
  if (!searchKeyword.value) {
    return allTopics.value;
  }
  return allTopics.value.filter(topic =>
      topic.includes(searchKeyword.value)
  );
});

// 处理上传错误
const handleUploadError = (error) => {
  console.error('上传错误:', error);
  uni.showToast({title: '上传失败，请重试', icon: 'none'});
};

// 搜索话题输入事件
const onSearchInput = (value) => {
  searchKeyword.value = value;
};

// 选择话题
const selectTopic = (topic) => {
  if (selectedTags.value.includes(topic)) {
    const index = selectedTags.value.indexOf(topic);
    selectedTags.value.splice(index, 1);
  } else if (selectedTags.value.length < 3) {
    selectedTags.value.push(topic);
  } else {
    uni.showToast({title: '最多选择3个话题', icon: 'none'});
  }
};

// 移除话题
const removeTag = (index) => {
  selectedTags.value.splice(index, 1);
};

// 提交表单
const submitForm = () => {
  // 防止重复点击
  if (loading.value) return;

  // 表单验证通过，提交数据
  submitContent();
};

// 提交内容到数据库
const submitContent = async () => {
  try {
    // 1. 开始加载，禁用按钮
    loading.value = true;

    // 2. 构造提交数据
    const postData = {
      userId: '123',
      content: formData.value.content.trim(),
      flie: JSON.stringify(formData.value.files),
      status: 1,
      tags: JSON.stringify(selectedTags.value)
    };

    // 3. 调用发布接口
    await publishArticle(postData);

    // 4. 发布成功
    uni.showToast({title: '发布成功', icon: 'success'});

    // 5. 重置表单并跳转
    setTimeout(() => {
      formData.value.content = '';
      formData.value.files = [];
      selectedTags.value = [];
      uni.reLaunch({url: '/pages/article/article'});
    }, 1500);

  } catch (error) {
    console.error('发布失败:', error);
    uni.showToast({title: '发布失败，请重试', icon: 'none'});
  } finally {
    // 无论成功失败，都结束加载状态
    loading.value = false;
  }
};
</script>

<style scoped>
/* 全局样式 */
.publish-page {
  padding: 20rpx;
  min-height: 100vh;
  background-color: #f5f5f5;
  font-size: 28rpx;
  color: #333;
}

/* 话题区域 */
.topic-container {
  display: flex;
  align-items: center;
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.topic-tag-but {
  display: inline-flex;
  align-items: center;
  background-color: #f0f9f5;
  border-radius: 10rpx;
  padding: 10rpx 20rpx;
  font-size: 28rpx;
  color: #39b54a;
  margin-right: 20rpx;
  transition: all 0.3s ease;
}

.topic-tag-but text {
  margin-left: 10rpx;
}

.topic-tag-but:active {
  background-color: #e0f5e5;
}

.selected-topics {
  display: flex;
  flex-wrap: wrap;
  flex-grow: 1;
}

.topic-tag {
  display: flex;
  align-items: center;
  background-color: #f0f0f0;
  padding: 8rpx 16rpx;
  margin-right: 16rpx;
  margin-bottom: 16rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  transition: all 0.3s ease;
}

.topic-tag:active {
  background-color: #e0e0e0;
}

.delete-tag {
  margin-left: 8rpx;
  color: #888;
  font-size: 24rpx;
  transition: all 0.3s ease;
}

.delete-tag:active {
  color: #ff4d4f;
}

/* 内容输入区域 */
.content-input {
  width: 100%;
  min-height: 300rpx;
  font-size: 32rpx;
  line-height: 1.6;
  padding: 10rpx 0;
}

/* 发布按钮 */
.form-button-container {
  padding: 40rpx 0;
}

.publish-btn {
  position: fixed;
  bottom: 60rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 140rpx;
  height: 140rpx;
  font-size: 32rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.15);
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 弹出层样式 */
.popup-content {
  width: 100%;
  max-height: 70vh;
  background-color: #fff;
  border-radius: 24rpx 24rpx 0 0;
  padding: 30rpx;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.popup-title {
  font-size: 36rpx;
  font-weight: bold;
}

.search-box {
  margin-bottom: 30rpx;
}

.topic-list {
  display: flex;
  flex-wrap: wrap;
}

.topic-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 30%;
  background-color: #f5f5f5;
  padding: 16rpx 24rpx;
  margin-right: 3%;
  margin-bottom: 20rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
  transition: all 0.3s ease;
}

.topic-item:active {
  background-color: #e8f5e9;
}

/* 响应式调整 */
@media (max-width: 375px) {
  .topic-item {
    width: 47%;
  }
}
</style>